<template>
  <div class="inventory-container">
    <!-- 搜索表单 -->
    <el-card class="search-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="title">
            <el-icon><i class="el-icon-goods" /></el-icon>
            <span>库存管理</span>
          </div>
          <div class="actions">
            <el-button type="success" @click="handleAdd">
              <el-icon><Plus /></el-icon> 新增
            </el-button>
            <el-button type="primary" @click="search" :loading="loading">
              <el-icon><i class="el-icon-search" /></el-icon> 查询
            </el-button>
          </div>
        </div>
      </template>

      <el-form :inline="true" :model="searchObj" label-width="80px" class="search-form">
        <!-- 水果：下拉显示名称，v-model 仍是 fruit_id -->
        <el-form-item label="水果">
          <el-select
              v-model="searchObj.fruit_id"
              placeholder="选择水果"
              clearable
              filterable
              :loading="fruitLoading"
              style="min-width: 220px"
          >
            <el-option
                v-for="f in fruits"
                :key="f.fruit_id"
                :label="f.fruit_name"
                :value="f.fruit_id"
            />
          </el-select>
        </el-form-item>

<!--        <el-form-item label="更新时间">-->
<!--          <el-date-picker-->
<!--              v-model="searchObj.dateRange"-->
<!--              type="daterange"-->
<!--              range-separator="至"-->
<!--              start-placeholder="开始日期"-->
<!--              end-placeholder="结束日期"-->
<!--              value-format="YYYY-MM-DD"-->
<!--              clearable-->
<!--          />-->
<!--        </el-form-item>-->

<!--        <el-form-item label="是否删除">-->
<!--          <el-select v-model="searchObj.isdela" placeholder="全部" clearable style="width: 160px">-->
<!--            <el-option label="0 - 正常" :value="0" />-->
<!--            <el-option label="1 - 删除" :value="1" />-->
<!--          </el-select>-->
<!--        </el-form-item>-->
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card shadow="hover">
      <el-table
          v-loading="loading"
          :data="tableData"
          style="width: 100%"
          stripe
          size="small"
          :fit="true"
          :header-cell-style="{ background: 'var(--el-fill-color-light)', fontWeight: 600 }"
          :empty-text="'暂无数据'"
      >
        <!-- 如果后端已联查返回 fruit_name，这里直接显示名称 -->
        <el-table-column prop="fruit_name" label="水果名称" min-width="120" show-overflow-tooltip />
        <el-table-column prop="current_stock" label="当前库存" width="120" align="right" />
        <el-table-column prop="last_update" label="最后更新时间" width="200">
          <template #default="{ row }">
            <span>{{ formatDateTime(row.last_update) }}</span>
          </template>
        </el-table-column>
<!--        <el-table-column prop="isdela" label="删除标记" width="120" align="center">-->
<!--          <template #default="{ row }">-->
<!--            <el-tag :type="row.isdela === 1 ? 'danger' : 'success'">-->
<!--              {{ row.isdela === 1 ? '已删除(1)' : '正常(0)' }}-->
<!--            </el-tag>-->
<!--          </template>-->
<!--        </el-table-column>-->

        <el-table-column label="操作" width="200" fixed="right" align="center">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>

        <template #empty>
          <el-empty description="没有找到相关库存记录">
            <el-button type="primary" text @click="handleAdd">去新增</el-button>
          </el-empty>
        </template>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
            v-model:current-page="searchObj.current"
            v-model:page-size="searchObj.limit"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            :page-sizes="[10, 20, 50, 100]"
            @current-change="loadData"
            @size-change="handleSizeChange"
        />
      </div>
    </el-card>

    <!-- 编辑弹窗：水果改为下拉显示名称 -->
    <el-dialog v-model="editDialogVisible" title="编辑库存" width="520px">
      <el-form :model="editForm" label-width="110px">
        <el-form-item label="库存ID">
          <el-input v-model="editForm.stock_id" disabled />
        </el-form-item>

        <el-form-item label="水果" required>
          <el-select
              v-model="editForm.fruit_id"
              placeholder="请选择水果"
              filterable
              :loading="fruitLoading"
              style="width: 100%"
          >
            <el-option
                v-for="f in fruits"
                :key="f.fruit_id"
                :label="f.fruit_name"
                :value="f.fruit_id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="当前库存" required>
          <el-input
              v-model.number="editForm.current_stock"
              placeholder="请输入当前库存"
              type="number"
              min="0"
          />
        </el-form-item>

        <el-form-item label="最后更新时间">
          <el-date-picker
              v-model="editForm.last_update"
              type="datetime"
              placeholder="选择时间"
              value-format="YYYY-MM-DD HH:mm:ss"
              format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%"
          />
        </el-form-item>

<!--        <el-form-item label="删除标记">-->
<!--          <el-select v-model="editForm.isdela" style="width: 100%">-->
<!--            <el-option label="0 - 正常" :value="0" />-->
<!--            <el-option label="1 - 删除" :value="1" />-->
<!--          </el-select>-->
<!--        </el-form-item>-->
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleEditSubmit">确认保存</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 新增弹窗：水果改为下拉显示名称 -->
    <el-dialog v-model="addDialogVisible" title="新增库存" width="520px">
      <el-form :model="addForm" label-width="110px">
        <el-form-item label="水果" required>
          <el-select
              v-model="addForm.fruit_id"
              placeholder="请选择水果"
              filterable
              :loading="fruitLoading"
              style="width: 100%"
          >
            <el-option
                v-for="f in fruits"
                :key="f.fruit_id"
                :label="f.fruit_name"
                :value="f.fruit_id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="当前库存" required>
          <el-input
              v-model.number="addForm.current_stock"
              placeholder="请输入当前库存"
              type="number"
              min="0"
          />
        </el-form-item>

        <el-form-item label="最后更新时间">
          <el-date-picker
              v-model="addForm.last_update"
              type="datetime"
              placeholder="选择时间（不填默认后端生成）"
              value-format="YYYY-MM-DD HH:mm:ss"
              format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%"
              clearable
          />
        </el-form-item>

        <el-form-item label="删除标记">
          <el-select v-model="addForm.isdela" style="width: 100%">
            <el-option label="0 - 正常" :value="0" />
            <el-option label="1 - 删除" :value="1" />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAddSubmit">确认新增</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { cloneDeep } from 'lodash'
import api from '@/api/inventory_api.js'
import fruitApi from '@/api/fruit_api.js'   // << 引入水果接口

// 表格数据
const tableData = ref([])
const total = ref(0)
const loading = ref(false)

// 查询参数
const searchObj = ref({
  current: 1,
  limit: 10,
  fruit_id: '',        // 下拉绑定 fruit_id
  isdela: undefined,   // 0/1，可清空
  dateRange: []        // ["YYYY-MM-DD","YYYY-MM-DD"]
})

// 水果下拉数据
const fruits = ref([])
const fruitLoading = ref(false)
const loadFruits = async () => {
  fruitLoading.value = true
  try {
    // 取较大分页，避免多次翻页加载；后端若有 isdela 字段，可附带过滤
    const res = await fruitApi.page({ current: 1, limit: 1000 })
    const list = res?.data || []
    fruits.value = list.map(x => ({
      fruit_id: x.fruit_id ?? x.id,
      fruit_name: x.fruit_name ?? x.name
    }))
  } catch (e) {
    console.error('加载水果列表失败:', e)
    ElMessage.error('加载水果列表失败')
  } finally {
    fruitLoading.value = false
  }
}

// 编辑弹窗
const editDialogVisible = ref(false)
const editForm = ref({
  stock_id: '',
  fruit_id: '',
  current_stock: 0,
  last_update: '',
  isdela: 0
})

// 新增弹窗
const addDialogVisible = ref(false)
const addForm = ref({
  fruit_id: '',
  current_stock: 0,
  last_update: '',
  isdela: 0
})

// 格式化日期显示
const formatDateTime = (val) => {
  if (!val) return ''
  const d = typeof val === 'number' ? new Date(val) : new Date(String(val).replace(/-/g, '/'))
  if (isNaN(d.getTime())) return String(val)
  const pad = (n) => (n < 10 ? '0' + n : n)
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
}

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    const params = {}
    for (const [k, v] of Object.entries(searchObj.value)) {
      if (v === '' || v === null || v === undefined) continue
      if (k === 'dateRange') {
        if (Array.isArray(v) && v.length === 2) {
          params.begin_date = v[0]
          params.end_date = v[1]
        }
      } else {
        params[k] = v
      }
    }
    const res = await api.page(params)
    tableData.value = res?.data || []
    total.value = res?.count || 0
  } catch (e) {
    console.error('加载库存数据失败:', e)
    ElMessage.error('加载数据失败')
    tableData.value = []
  } finally {
    loading.value = false
  }
}

const search = async () => {
  searchObj.value.current = 1
  await loadData()
}

// 新增
const handleAdd = () => {
  addForm.value = {
    fruit_id: '',
    current_stock: 0,
    last_update: '',
    isdela: 0
  }
  addDialogVisible.value = true
}

const handleAddSubmit = async () => {
  if (!addForm.value.fruit_id) {
    ElMessage.warning('请选择水果')
    return
  }
  if (addForm.value.current_stock === '' || addForm.value.current_stock === null || addForm.value.current_stock < 0) {
    ElMessage.warning('请输入正确的当前库存')
    return
  }
  try {
    await api.add(addForm.value)
    ElMessage.success('新增成功')
    addDialogVisible.value = false
    loadData()
  } catch (e) {
    console.error('新增失败:', e)
    ElMessage.error('新增失败，请重试')
  }
}

// 编辑
const handleEdit = (row) => {
  editForm.value = cloneDeep(row)
  if (typeof editForm.value.last_update === 'number') {
    const d = new Date(editForm.value.last_update)
    const pad = (n) => (n < 10 ? '0' + n : n)
    editForm.value.last_update =
        `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
  }
  editDialogVisible.value = true
}

const handleEditSubmit = async () => {
  if (!editForm.value.stock_id) {
    ElMessage.warning('缺少库存ID')
    return
  }
  if (!editForm.value.fruit_id) {
    ElMessage.warning('请选择水果')
    return
  }
  if (editForm.value.current_stock === '' || editForm.value.current_stock === null || editForm.value.current_stock < 0) {
    ElMessage.warning('请输入正确的当前库存')
    return
  }
  try {
    await api.edit(editForm.value)
    ElMessage.success('保存成功')
    editDialogVisible.value = false
    loadData()
  } catch (e) {
    console.error('保存失败:', e)
    ElMessage.error('保存失败，请重试')
  }
}

// 删除
const handleDelete = async (index, row) => {
  try {
    const confirm = await ElMessageBox.confirm(
        `确定要删除库存记录 ID=${row.stock_id} 吗？`,
        '警告',
        { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning', draggable: true }
    )
    if (confirm === 'confirm') {
      await api.del(row.stock_id)
      ElMessage.success('删除成功')
      loadData()
    }
  } catch (e) {
    if (!(e instanceof Error && e.message === 'cancel')) {
      console.error('删除失败:', e)
      ElMessage.error('删除失败')
    }
  }
}

// 分页大小变更
const handleSizeChange = (val) => {
  searchObj.value.limit = val
  searchObj.value.current = 1
  loadData()
}

onMounted(() => {
  loadFruits()
  loadData()
})
</script>

<style scoped>
.inventory-container {
  padding: 18px;
}

.search-card {
  margin-bottom: 16px;
  border-radius: 14px;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.card-header .title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
}

.card-header .actions {
  display: flex;
  gap: 8px;
}

.search-form :deep(.el-form-item) {
  margin-bottom: 12px;
}

.pagination {
  margin-top: 14px;
  display: flex;
  justify-content: center;
}

:deep(.el-button) {
  margin-right: 8px;
}
</style>
